const express = require('express');
const router = express.Router();
const multer = require('multer');
const imageController = require('../controllers/imageController');
const path = require('path');
const fs = require('fs');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 确保上传目录存在
    const uploadDir = path.join(__dirname, '../../uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成安全的文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, uniqueSuffix + path.extname(file.originalname));
  }
});

const fileFilter = (req, file, cb) => {
  // 验证文件类型
  if (!file.mimetype.startsWith('image/')) {
    cb(new Error('只能上传图片文件'), false);
    return;
  }
  cb(null, true);
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB
    files: 1 // 一次只能上传一个文件
  },
  fileFilter: fileFilter
});

// 错误处理中间件
const handleError = (err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({ error: '文件大小不能超过10MB' });
    }
    return res.status(400).json({ error: '文件上传错误' });
  }
  if (err.message === '只能上传图片文件') {
    return res.status(400).json({ error: err.message });
  }
  next(err);
};

// 图片压缩
router.post('/compress', upload.single('image'), handleError, imageController.compressImage);

// 图片剪裁
router.post('/crop', upload.single('image'), imageController.cropImage);

// 图片格式转换
router.post('/convert', upload.single('image'), imageController.convertImage);

// 添加水印
router.post('/watermark', upload.single('image'), imageController.addWatermark);

// 下载处理后的图片
router.get('/download/:filename', imageController.downloadImage);

module.exports = router; 